package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.mapper.WsdCanteenBalanceMapper;
import com.ruoyi.business.mapper.WsdCanteensMapper;
import com.ruoyi.business.mapper.WsdStudentsMapper;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.WsdCanteensDTO;
import com.ruoyi.common.core.domain.dto.WsdCanteensOrderDTO;
import com.ruoyi.common.core.domain.dto.WsdOrderImportDTO;
import com.ruoyi.common.core.domain.entity.*;

import com.ruoyi.common.core.domain.vo.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.date.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 饭堂信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@Slf4j
@Service
public class WsdCanteensServiceImpl implements IWsdCanteensService
{
    @Autowired
    private WsdCanteensMapper wsdCanteensMapper;

    @Autowired
    private WsdCanteenBalanceMapper wsdCanteenBalanceMapper;
    @Autowired
    private IWsdRechargeRefundService wsdRechargeRefundService;
    @Autowired
    private WsdStudentsMapper wsdStudentsMapper;
    @Autowired
    private IWsdPaymentRecordsService wsdPaymentRecordsService;
    @Autowired
    private FuiouNotifyServiceImpl fuiouNotifyService;
    @Autowired
    private IWsdCanteenBalanceService wsdCanteenBalanceService;
    /**
     * 查询饭堂信息
     *
     * @param id 饭堂信息主键
     * @return 饭堂信息
     */
    @Override
    public WsdCanteens selectWsdCanteensById(Long id)
    {
        return wsdCanteensMapper.selectWsdCanteensById(id);
    }

    /**
     * 查询饭堂信息列表
     *
     * @param wsdCanteens 饭堂信息
     * @return 饭堂信息
     */
    @Override
    public List<WsdCanteens> selectWsdCanteensList(WsdCanteens wsdCanteens) {
        return wsdCanteensMapper.selectWsdCanteensList(wsdCanteens);
    }

    @Override
    public List<WsdCanteensOrderVO> orderFoodList(WsdCanteensOrderDTO wsdCanteensOrderDTO){
        if (wsdCanteensOrderDTO.getStartDate()!=null&&wsdCanteensOrderDTO.getEndDate()!=null){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 解析日期部分
            LocalDate startLocalDate = LocalDate.parse(wsdCanteensOrderDTO.getStartDate(), formatter);
            LocalDate endLocalDate = LocalDate.parse(wsdCanteensOrderDTO.getEndDate(), formatter);

            // 设置开始时间为当天的00:00:00
            LocalDateTime startDate = startLocalDate.atStartOfDay();

            // 设置结束时间为当天的23:59:59
            LocalDateTime endDate = endLocalDate.atTime( LocalTime.MAX);
            wsdCanteensOrderDTO.setStartTime( startDate );
            wsdCanteensOrderDTO.setEndTime( endDate );
        }
        //获取配置Id
        //获取配置ConfigId
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()||wsdCanteensOrderDTO.getSchoolId()!=null) {
            String currentDateString = DateTimeUtil.getCurrentDateString();
            RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester( wsdCanteensOrderDTO.getSchoolId(), currentDateString );
            if (rechargeRefundVO == null) {
                throw new RuntimeException( "该学校还没有配置收费规则,查询失败，请联系管理员!" );
            }
            wsdCanteensOrderDTO.setConfigId( rechargeRefundVO.getConfigId() );
            startPage();
            List<WsdCanteensOrderVO> list = wsdCanteenBalanceMapper.orderFoodList( wsdCanteensOrderDTO );
            for (WsdCanteensOrderVO wsdCanteensOrderVO : list) {
                wsdCanteensOrderVO.setReturnFee( wsdCanteensOrderVO.getTotalFee().subtract( wsdCanteensOrderVO.getBalanceFee() ) );
                Integer meals = 0;
                if (!BigDecimal.ZERO.equals( wsdCanteensOrderVO.getTotalFee() )) {
                    if (wsdCanteensOrderVO.getMealType() == 0) {
                        if (rechargeRefundVO.getBreakfastFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getBreakfastFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 1) {
                        if (rechargeRefundVO.getLunchFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getLunchFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 2) {
                        if (rechargeRefundVO.getDinnerFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getDinnerFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 3) {
                        BigDecimal resultA = BigDecimal.ZERO;
                        BigDecimal resultB = BigDecimal.ZERO;
                        BigDecimal resultC = BigDecimal.ZERO;
                        if (rechargeRefundVO.getDinnerFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultA = rechargeRefundVO.getTotalDinnerFee().divide( rechargeRefundVO.getDinnerFee(), 0, RoundingMode.HALF_UP );
                        }
                        if (rechargeRefundVO.getLunchFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultB = rechargeRefundVO.getTotalLunchFee().divide( rechargeRefundVO.getLunchFee(), 0, RoundingMode.HALF_UP );
                        }
                        if (rechargeRefundVO.getBreakfastFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultC = rechargeRefundVO.getTotalBreakfastFee().divide( rechargeRefundVO.getBreakfastFee(), 0, RoundingMode.HALF_UP );
                        }
                        meals = resultA.add( resultB ).add( resultC ).intValue();
                    }
                }
                wsdCanteensOrderVO.setMeals( meals );
            }
            return list;
        }else {
            startPage();
            List<WsdCanteensOrderVO> list = wsdCanteenBalanceMapper.orderFoodList( wsdCanteensOrderDTO );
            for (WsdCanteensOrderVO wsdCanteensOrderVO : list) {
                String currentDateString = DateTimeUtil.getCurrentDateString();
                RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester( wsdCanteensOrderVO.getSchoolsId(), currentDateString );
                if (rechargeRefundVO == null) {
                    continue;
                }
                Integer meals = 0;
                if (!BigDecimal.ZERO.equals( wsdCanteensOrderVO.getTotalFee() )) {
                    if (wsdCanteensOrderVO.getMealType() == 0) {
                        if (rechargeRefundVO.getBreakfastFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getBreakfastFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 1) {
                        if (rechargeRefundVO.getLunchFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getLunchFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 2) {
                        if (rechargeRefundVO.getDinnerFee().compareTo( BigDecimal.ZERO ) != 0) {
                            BigDecimal result = wsdCanteensOrderVO.getTotalFee().divide( rechargeRefundVO.getDinnerFee(), 0, RoundingMode.HALF_UP );
                            meals = result.intValue();
                        }
                    } else if (wsdCanteensOrderVO.getMealType() == 3) {
                        BigDecimal resultA = BigDecimal.ZERO;
                        BigDecimal resultB = BigDecimal.ZERO;
                        BigDecimal resultC = BigDecimal.ZERO;
                        if (rechargeRefundVO.getDinnerFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultA = rechargeRefundVO.getTotalDinnerFee().divide( rechargeRefundVO.getDinnerFee(), 0, RoundingMode.HALF_UP );
                        }
                        if (rechargeRefundVO.getLunchFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultB = rechargeRefundVO.getTotalLunchFee().divide( rechargeRefundVO.getLunchFee(), 0, RoundingMode.HALF_UP );
                        }
                        if (rechargeRefundVO.getBreakfastFee().compareTo( BigDecimal.ZERO ) != 0) {
                            resultC = rechargeRefundVO.getTotalBreakfastFee().divide( rechargeRefundVO.getBreakfastFee(), 0, RoundingMode.HALF_UP );
                        }
                        meals = resultA.add( resultB ).add( resultC ).intValue();
                    }
                }
                wsdCanteensOrderVO.setMeals( meals );
                wsdCanteensOrderVO.setReturnFee( wsdCanteensOrderVO.getTotalFee().subtract( wsdCanteensOrderVO.getBalanceFee() ) );
            }
            return list;
        }
    }

    /**
     * 新增饭堂信息
     *
     * @param wsdCanteensDTO 饭堂信息
     * @return 结果
     */
    @Override
    public int insertWsdCanteens(WsdCanteensDTO wsdCanteensDTO) {
        //String imagesAsString = String.join("||", wsdCanteensDTO.getImages());
        String imagesAsString = wsdCanteensDTO.getImages() != null ? String.join("||", wsdCanteensDTO.getImages()) : "";
        WsdCanteens wsdCanteens = new WsdCanteens();
        BeanUtils.copyProperties(wsdCanteensDTO,wsdCanteens);
        wsdCanteens.setImages(imagesAsString);
        wsdCanteens.setCreateTime(DateUtils.getNowDate());
        return wsdCanteensMapper.insertWsdCanteens(wsdCanteens);
    }

    /**
     * 修改饭堂信息
     *
     * @param wsdCanteensDTO 饭堂信息
     * @return 结果
     */
    @Override
    public int updateWsdCanteens(WsdCanteensDTO wsdCanteensDTO) {
//        String imagesAsString = String.join("||", wsdCanteensDTO.getImages());
        // 检查wsdCanteensDTO.getImages()是否为null
        String imagesAsString = wsdCanteensDTO.getImages() != null ? String.join("||", wsdCanteensDTO.getImages()) : "";
        WsdCanteens wsdCanteens = new WsdCanteens();
        BeanUtils.copyProperties(wsdCanteensDTO,wsdCanteens);
        wsdCanteens.setId(wsdCanteensDTO.getId());
        wsdCanteens.setImages(imagesAsString);
        wsdCanteens.setUpdateTime(DateUtils.getNowDate());
        return wsdCanteensMapper.updateWsdCanteens(wsdCanteens);
    }

    /**
     * 批量删除饭堂信息
     *
     * @param ids 需要删除的饭堂信息主键
     * @return 结果
     */
    @Override
    public int deleteWsdCanteensByIds(Long[] ids) {
        return wsdCanteensMapper.deleteWsdCanteensByIds(ids);
    }

    /**
     * 删除饭堂信息信息
     *
     * @param id 饭堂信息主键
     * @return 结果
     */
    @Override
    public int deleteWsdCanteensById(Long id) {
        return wsdCanteensMapper.deleteWsdCanteensById(id);
    }

    /**
     * 获取饭堂图片
     *
     * @param schoolId
     * @return
     */
    @Override
    public WsdCanteensVO selectWsdCanteensBySchoolId(Long schoolId) {
        WsdCanteens wsdCanteens = new WsdCanteens();
        wsdCanteens.setSchoolId(schoolId);
        WsdCanteensVO wsdCanteensVO = new WsdCanteensVO();
        List<WsdCanteens> wsdCanteensList = wsdCanteensMapper.selectWsdCanteensList(wsdCanteens);
        //拿出wsdCanteensList的第一条
        if (wsdCanteensList.size() > 0) {
            WsdCanteens canteens = wsdCanteensList.get(0);
            List<String> imagesList = new ArrayList<>();
            // 使用"||"作为分隔符分割图片信息字符串
            String[] images = canteens.getImages().split("\\|\\|");
            for (String image : images) {
                imagesList.add(image);
            }
            // 将从数据库查询的WsdCompany对象的属性复制到CompanyVO对象中
            BeanUtils.copyProperties(canteens, wsdCanteensVO);
            // 设置CompanyVO对象的图片列表和证书列表
            wsdCanteensVO.setImages(imagesList);
        }
        // 返回wsdCanteensVO对象
        return wsdCanteensVO;
    }
    @Override
    public AjaxResult addOrdering(WsdCanteensOrderDTO wsdCanteensOrderDTO) {
        //检查是否在线上已缴费
            if (wsdCanteensOrderDTO.getPayAmount() == null){
                return AjaxResult.error("请输入充值金额！！");
            }
        WsdStudentsChatINVO wsdStudentsChatINVO = new WsdStudentsChatINVO();
            wsdStudentsChatINVO.setIdentityNumber( wsdCanteensOrderDTO.getIdentityNumber() );
            wsdStudentsChatINVO.setClassId( wsdCanteensOrderDTO.getClassId() );
            //检查学生
            WsdStudentsChatINVO wsdStudents = wsdStudentsMapper.selectWsdStudentsByIdentityNumber1(wsdStudentsChatINVO);
            if (wsdStudents == null){
                return AjaxResult.error("该班级找不到这个学生的身份证信息，请检查学生信息后再重试！！");
            } else if (wsdStudents.getSchoolId()==null) {
                return AjaxResult.error("该学生的学校信息不存在，请检查学生信息后再重试！！");
            }
            if (!wsdStudents.getName().equals( wsdCanteensOrderDTO.getStudentName() )){
                return AjaxResult.error("该学生的姓名与班级里面学生信息不一致，请检查学生信息后再重试！！");
            }
            if (!wsdStudents.getParentsPhone().equals( wsdCanteensOrderDTO.getParentsPhone() )){
                return AjaxResult.error("该学生的家长手机号与班级里面学生信息不一致，请检查学生信息后再重试！！");
            }

            //获取学校的配置
            String currentDateString = DateTimeUtil.getCurrentDateString();
            RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester(wsdStudents.getSchoolId(),currentDateString);
            if (rechargeRefundVO == null){
                return AjaxResult.error("该学校没有配置学期饭堂的收费配置，请检查学校配置或联系财务后再重试！！");
            }
            String orderId = fuiouNotifyService.generateOrderId();
            //新增流水
            WsdPaymentRecords wsdPaymentRecords = new WsdPaymentRecords();
            wsdPaymentRecords.setTransactionId(orderId);   //订单号
            wsdPaymentRecords.setUserId(wsdStudents.getId()); //用户id
            wsdPaymentRecords.setStudentId(wsdStudents.getId());  //学生id
            wsdPaymentRecords.setStudentName(wsdStudents.getName());  //学生姓名
            wsdPaymentRecords.setSchoolName(wsdStudents.getSchoolName()); //学校名称
            wsdPaymentRecords.setSchoolsId(wsdStudents.getSchoolId()); //学校id
            wsdPaymentRecords.setGradeName(wsdStudents.getGradeName()); //年级
            wsdPaymentRecords.setGradeId( wsdStudents.getGradeId() );
            wsdPaymentRecords.setClassId( wsdStudents.getClassId() );
            wsdPaymentRecords.setClassName(wsdStudents.getClassName()); //班级
            wsdPaymentRecords.setIdentityNumber(wsdStudents.getIdentityNumber()); //身份证暂时没有
            wsdPaymentRecords.setParentMobile(wsdStudents.getParentsPhone());  //家长手机号
            wsdPaymentRecords.setRechargeTime(LocalDateTime.now()); //充值时间
            wsdPaymentRecords.setFeeTime( LocalDateTime.now() );
            wsdPaymentRecords.setFeeItemName("学生餐费"); //缴费项目名称
            wsdPaymentRecords.setMealType(wsdCanteensOrderDTO.getMealType());  //缴费类型 (0: 早餐, 1: 午餐, 2: 晚餐)
            Integer mealType = wsdCanteensOrderDTO.getMealType();
            switch (mealType){
                case 0:
                    wsdPaymentRecords.setFeeAccountName("学生早餐费"); //缴费账单名称
                    break;
                case 1:
                    wsdPaymentRecords.setFeeAccountName("学生午餐费"); //缴费账单名称
                    break;
                case 2:
                    wsdPaymentRecords.setFeeAccountName("学生晚餐费"); //缴费账单名称
                    break;
                default:
                    wsdPaymentRecords.setFeeAccountName("学生总餐费"); //缴费账单名称
                    break;
            }
            wsdPaymentRecords.setMealType( mealType );
            wsdPaymentRecords.setFeeAccountName("学生餐费"); //缴费账单名称
            wsdPaymentRecords.setConfigId(rechargeRefundVO.getConfigId()); //学期id
            wsdPaymentRecords.setIsPaid(true); //是否支付 (0: 未支付, 1: 已支付)
            wsdPaymentRecords.setTotalFee(wsdCanteensOrderDTO.getPayAmount());
            wsdPaymentRecords.setBalanceFee( wsdCanteensOrderDTO.getPayAmount() );
            wsdPaymentRecords.setRechargeType( wsdCanteensOrderDTO.getRechargeType() );
            //进行新增
            wsdPaymentRecordsService.save(wsdPaymentRecords);
            log.info("流水新增成功studentId【】"+wsdStudents.getId());
            //新增余额
            wsdCanteenBalanceService.rechargeBalance(wsdPaymentRecords.getStudentId(),wsdPaymentRecords.getSchoolsId(),wsdCanteensOrderDTO.getPayAmount(),wsdPaymentRecords.getMealType());
            log.info("更新余额成功studentId【】"+wsdStudents.getId());
            return AjaxResult.success();
    }

    /**
     * 导入
     */
    @Override
    public AjaxResult importOrdering(List<WsdOrderImportDTO> wsdOrderImportDTOList, Long classId, Long gradeId){
        SysUser sysUser = getLoginUser().getUser();
        if (sysUser.getSchoolId()==null){
            return AjaxResult.error("导入失败，请联系管理员！！");
        }
        //获取学校的配置
        String currentDateString = DateTimeUtil.getCurrentDateString();
        RechargeRefundVO rechargeRefundVO = wsdRechargeRefundService.existsActiveSemester(sysUser.getSchoolId(),currentDateString);
        if (rechargeRefundVO == null){
            return AjaxResult.error("该学校没有配置学期饭堂的收费配置");
        }
        //导入结果
        Integer success = 0;
        Integer failed = 0;
        //失败
        List<WsdOrderImportDTO> failedList = new ArrayList<>();
        for (WsdOrderImportDTO wsdOrderImportDTO : wsdOrderImportDTOList){
            if (wsdOrderImportDTO.getLunchAmount()==null&&wsdOrderImportDTO.getDinnerAmount()==null&&wsdOrderImportDTO.getLunchAmount()==null&&wsdOrderImportDTO.getStudentName()==null&&wsdOrderImportDTO.getIdentityNumber()==null&&wsdOrderImportDTO.getParentsPhone()==null){
                continue;
            }
            if (wsdOrderImportDTO.getStudentName()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "学生姓名为空" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if (wsdOrderImportDTO.getIdentityNumber()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "学生身份证号为空" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if (wsdOrderImportDTO.getParentsPhone()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "家长手机号为空" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            //去空格
            wsdOrderImportDTO.setStudentName(wsdOrderImportDTO.getStudentName().replaceAll("\\s", ""));
            wsdOrderImportDTO.setIdentityNumber(wsdOrderImportDTO.getIdentityNumber().replaceAll("\\s", ""));
            wsdOrderImportDTO.setParentsPhone(wsdOrderImportDTO.getParentsPhone().replaceAll("\\s", ""));
            //校验金额的格式
            if ( wsdOrderImportDTO.getBreakfastAmount()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "早餐金额的格式错误,只能填写纯数字，不能为空或者其他值" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if ( wsdOrderImportDTO.getLunchAmount()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "午餐金额的格式错误,只能填写纯数字，不能为空或者其他值" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if ( wsdOrderImportDTO.getDinnerAmount()==null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "晚餐金额的格式错误,只能填写纯数字，不能为空或者其他值" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            BigDecimal payAmount = BigDecimal.ZERO;
            //判断类型
            //早餐 0
            if (wsdOrderImportDTO.getBreakfastAmount().compareTo(BigDecimal.ZERO)>0
                    && wsdOrderImportDTO.getLunchAmount().compareTo(BigDecimal.ZERO)==0
                    && wsdOrderImportDTO.getDinnerAmount().compareTo(BigDecimal.ZERO)==0){
                wsdOrderImportDTO.setMealType( 0 );
            }else if (wsdOrderImportDTO.getBreakfastAmount().compareTo(BigDecimal.ZERO)==0
                    && wsdOrderImportDTO.getLunchAmount().compareTo(BigDecimal.ZERO)>0
                    && wsdOrderImportDTO.getDinnerAmount().compareTo(BigDecimal.ZERO)==0){
                //午餐 1
                wsdOrderImportDTO.setMealType( 1 );
            }else if (wsdOrderImportDTO.getBreakfastAmount().compareTo(BigDecimal.ZERO)==0
                    && wsdOrderImportDTO.getLunchAmount().compareTo(BigDecimal.ZERO)==0
                    && wsdOrderImportDTO.getDinnerAmount().compareTo(BigDecimal.ZERO)>0){
                //晚餐 2
                wsdOrderImportDTO.setMealType( 2 );
            }else {
                //合计 3
                wsdOrderImportDTO.setMealType( 3 );
            }
            payAmount = wsdOrderImportDTO.getBreakfastAmount().add( wsdOrderImportDTO.getLunchAmount() ).add( wsdOrderImportDTO.getDinnerAmount() );
            WsdStudentsChatINVO wsdStudentsChatINVO = new WsdStudentsChatINVO();
            wsdStudentsChatINVO.setIdentityNumber( wsdOrderImportDTO.getIdentityNumber() );
//            wsdStudentsChatINVO.setClassId( classId );
            //检查学生
            WsdStudentsChatINVO wsdStudents = wsdStudentsMapper.selectWsdStudentsByIdentityNumber1(wsdStudentsChatINVO);
            if (wsdStudents == null){
                failed++;
                wsdOrderImportDTO.setFailureResult( "此班级找不到该学生-身份证号匹配失败" );
                failedList.add( wsdOrderImportDTO );
                continue;
            } else if (wsdStudents.getSchoolId()==null) {
                failed++;
                wsdOrderImportDTO.setFailureResult( "该学生的学校信息不存在" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if (!wsdStudents.getName().equals( wsdOrderImportDTO.getStudentName() )){
                failed++;
                wsdOrderImportDTO.setFailureResult( "该学生的姓名与学生信息名称不一致" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }
            if (!wsdStudents.getParentsPhone().equals( wsdOrderImportDTO.getParentsPhone() )){
                failed++;
                wsdOrderImportDTO.setFailureResult( "该学生的家长手机号与学生信息不一致" );
                failedList.add( wsdOrderImportDTO );
                continue;
            }

            //开始插入
            String orderId = fuiouNotifyService.generateOrderId();
            //新增流水
            WsdPaymentRecords wsdPaymentRecords = new WsdPaymentRecords();
            wsdPaymentRecords.setTransactionId(orderId);   //订单号
            wsdPaymentRecords.setUserId(wsdStudents.getId()); //用户id
            wsdPaymentRecords.setStudentId(wsdStudents.getId());  //学生id
            wsdPaymentRecords.setStudentName(wsdStudents.getName());  //学生姓名
            wsdPaymentRecords.setSchoolName(wsdStudents.getSchoolName()); //学校名称
            wsdPaymentRecords.setSchoolsId(wsdStudents.getSchoolId()); //学校id
            wsdPaymentRecords.setGradeName(wsdStudents.getGradeName()); //年级
            wsdPaymentRecords.setGradeId( wsdStudents.getGradeId() );
            wsdPaymentRecords.setClassId( wsdStudents.getClassId() );
            wsdPaymentRecords.setClassName(wsdStudents.getClassName()); //班级
            wsdPaymentRecords.setIdentityNumber(wsdStudents.getIdentityNumber()); //身份证暂时没有
            wsdPaymentRecords.setParentMobile(wsdStudents.getParentsPhone());  //家长手机号
            wsdPaymentRecords.setRechargeTime(LocalDateTime.now()); //充值时间
            wsdPaymentRecords.setFeeTime( LocalDateTime.now() );
            wsdPaymentRecords.setFeeItemName("学生餐费"); //缴费项目名称
            wsdPaymentRecords.setMealType(wsdOrderImportDTO.getMealType());  //缴费类型 (0: 早餐, 1: 午餐, 2: 晚餐)
            Integer mealType = wsdOrderImportDTO.getMealType();
            switch (mealType){
                case 0:
                    wsdPaymentRecords.setFeeAccountName("学生早餐费"); //缴费账单名称
                    break;
                case 1:
                    wsdPaymentRecords.setFeeAccountName("学生午餐费"); //缴费账单名称
                    break;
                case 2:
                    wsdPaymentRecords.setFeeAccountName("学生晚餐费"); //缴费账单名称
                    break;
                default:
                    wsdPaymentRecords.setFeeAccountName("学生总餐费"); //缴费账单名称
                    break;
            }
            wsdPaymentRecords.setMealType( mealType );
            wsdPaymentRecords.setFeeAccountName("学生餐费"); //缴费账单名称
            wsdPaymentRecords.setConfigId(rechargeRefundVO.getConfigId()); //学期id
            wsdPaymentRecords.setIsPaid(true); //是否支付 (0: 未支付, 1: 已支付)
            wsdPaymentRecords.setTotalFee(payAmount);
            wsdPaymentRecords.setBalanceFee( payAmount );
            wsdPaymentRecords.setRechargeType( 2 );
            //进行新增
            boolean i = wsdPaymentRecordsService.save(wsdPaymentRecords);
            if (!i){
                failed++;
                wsdOrderImportDTO.setFailureResult( "流水新增失败，请检查数据后再重试！！" );
                failedList.add( wsdOrderImportDTO );
                log.info("流水新增失败studentId【】"+wsdStudents.getId());
                continue;
            }
            log.info("流水新增成功studentId【】"+wsdStudents.getId());
            //新增余额
            if (wsdPaymentRecords.getMealType()==3){
                wsdCanteenBalanceService.rechargeBalance1(wsdPaymentRecords.getStudentId(),wsdPaymentRecords.getSchoolsId(),payAmount,wsdOrderImportDTO.getBreakfastAmount(),wsdOrderImportDTO.getLunchAmount(),wsdOrderImportDTO.getDinnerAmount(),wsdPaymentRecords.getMealType());
            }else {
                wsdCanteenBalanceService.rechargeBalance(wsdPaymentRecords.getStudentId(),wsdPaymentRecords.getSchoolsId(),payAmount,wsdPaymentRecords.getMealType());
            }
            log.info("更新余额成功studentId【】"+wsdStudents.getId());
            success++;
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put( "successCount", success );
        resultMap.put( "errorCount" , failed);
        resultMap.put("result", failedList);
        AjaxResult result = AjaxResult.success();
        result.put("data",resultMap); // 或者根据框架要求，可能需要直接返回jsonResult
        return result;
    }
}
